#include "heightmap.h"
#include <cassert>

cHeightmap::cHeightmap():m_scale(2.0f),m_offset(100.0f){

}


void cHeightmap::LoadRAW(string rawfiles,int rows,int cols)
{
	m_rows = rows;  m_cols = cols;
	size_t size = m_rows*m_cols;
	vecHeightmap.resize(size);
	char* inFile = new char[size];
	LoadRaw(rawfiles,&inFile,size);
	for(int i = 0;i!=size;++i)
	{
		vecHeightmap[i] = float(((unsigned char)inFile[i])*m_scale + m_offset);
	}
	delete [] inFile;
	Filter3x3();
}

void cHeightmap::Filter3x3()
{
	for(int i = 0;i<m_rows;++i)
	{
		for(int j = 0;j<m_cols;++j)
		{
			FilterPixel3x3(i,j);
		}
	}
}
float cHeightmap::GetHeight(int row,int col)
{
	assert(inBounds(row,col));
	return vecHeightmap[ row * m_cols + col ];
}
void cHeightmap::SetHeight(int row,int col,float height)
{
	assert(inBounds(row,col));
	vecHeightmap[row*m_cols+col] = height;
}
void cHeightmap::FilterPixel3x3(int row,int col)
{
	assert( inBounds( row, col ) );
	float accu = 0.0f;
	int samples = 1;
	for(int m = row-1;m<=row+1;++m)
	{
		for(int n = col-1;n<=col+1;++n)
		{
			if(inBounds(m,n))
			{
				accu += GetHeight(m,n);
				++samples;
			}
		}
	}
	SetHeight(row,col,accu/samples);
}
bool cHeightmap::inBounds(int row,int col)
{
	if( row < 0 || col < 0 || row >= m_rows || col >= m_cols )
		return false;
	return true;
}

